package com.masasdani.googlepay.controller;

import com.alibaba.fastjson2.JSONObject;
import com.masasdani.paypal.domain.Orders;
import com.masasdani.paypal.service.PayPalSubscriptionService;
import com.masasdani.paypal.service.PaypalService;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;


import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * paypal支付控制类
 */
@Controller
@RequestMapping("/googlepay/")
public class GooglePayController {

	private static final String GOOGLE_PAY_API_URL = "https://www.googleapis.com/androidpublisher/v3/applications/com.example.yourapp/inappproducts/your.product.id/purchases/tokens/";

	public static final String PAYPAL_REFUND_URL = "refund/success";

	private Logger log = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private PaypalService paypalService;

	@Autowired
	private PayPalSubscriptionService payPalSubscriptionService;


	/**
	 * 创建googlepay订单
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(method = RequestMethod.POST, value = "createOrders")
	public static Orders createOrder(Orders orders)  {
		boolean sandbox = true;
		//生成订单
//		orders.setOrderTime(DateUtils.getNowDate());
//		orders.setOrderNumber(OrderUtils.getOrderCode(Integer.parseInt(String.valueOf(userId))));
//		orders.setQuantity(SysConstantUtils.INT_1);
//		orders.setUserId(userId);
//		orders.setDueTime(DateUtils.getDateByNowDateAndMonth(DateUtils.getNowDate(),goods.getIncreaseMonth()));
//		orders.setAmount(goods.getPrice());
//		orders.setCurrency(goods.getCurrency());
//		orders.setPayMethod(SysConstantUtils.INT_1);
//		orders.setCreateTime(DateUtils.getNowDate());
//		orders.setStatus(SysConstantUtils.INT_0);
//		orders.setPaymentId(payment.getId());
//		ordersService.insertOrders(orders);

		return orders;
	}


	/**
     * googlepay支付成功后验证
	 * @param paymentToken
     * @return
     * @throws IOException
	 */
	@RequestMapping(method = RequestMethod.GET, value = "validateReceipt")
	public static Boolean validateReceipt(@RequestBody String paymentToken) throws IOException {
		try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
			HttpPost httpPost = new HttpPost(GOOGLE_PAY_API_URL);

			String apiKey = "YOUR_API_KEY";
			// Set headers
			httpPost.setHeader("Content-Type", "application/json");
			httpPost.setHeader("Authorization", "Bearer " + apiKey);

			// Create JSON object for the request body
			JSONObject json = new JSONObject();
			json.put("jwt", paymentToken);

			// Set request body
			StringEntity entity = new StringEntity(json.toString());
			httpPost.setEntity(entity);

			try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
				String responseBody = EntityUtils.toString(response.getEntity());
				JSONObject responseJson = JSONObject.parseObject(responseBody);
				if (responseJson.getBoolean("valid")) {

					//TODO 支付成功后需要更新订单表

					//TODO 支付成功后需要更新用户时长

					return true;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}



		return false;
	}

	/**
	 * 支付退款
	 * @param orderId
	 * @param refundRequest
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, value = PAYPAL_REFUND_URL)
	public Map<String, Object> processRefund(@RequestParam("orderId") String orderId, @RequestBody Map<String, Object> refundRequest) {
		String reason = (String) refundRequest.get("reason");

		// 假设这里处理退款并将结果存入数据库
		Map<String, Object> response = new HashMap<>();
		response.put("orderId", orderId);
		response.put("status", "REFUNDED");
		response.put("reason", reason);

		//TODO 退款成功更新订单表

		//TODO 退款成功更新用户时长

		return response;
	}

}
